/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.ntb.controllers;

import com.ntb.common.SecuredAction;
import com.ntb.controllers.forms.GroupForm;
import com.ntb.entities.UserGroups;
import com.ntb.models.UserGroupsDAO;
import com.ntb.models.impl.UserGroupsDAOImpl;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 *
 * @author Thinh Hung
 */
public class GroupAction extends SecuredAction {

    @Override
    public ActionForward ntbExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) {
        GroupForm groupForm = (GroupForm) form;

        ActionForward forward = null;
        String action = groupForm.getAction();
        if (("save").equalsIgnoreCase(action)) {
            UserGroups group = new UserGroups();
            UserGroupsDAO groupDao = new UserGroupsDAOImpl();
            group.setGroupID(groupForm.getGroupID());
            group.setGroupName(groupForm.getGroupName());

            if (group.getGroupID() > 0) {
                UserGroups temp = groupDao.getRow(group.getGroupID());
                if (temp == null) {
                    request.setAttribute("errorMessage", "Group not found!");
                } else {
                    groupDao.update(group);
                    request.setAttribute("successMessage", "The group \" " + group.getGroupName() + " \" has been saved.");
                }
            } else {
                groupDao.add(group);
                request.setAttribute("successMessage", "The group \" " + group.getGroupName() + " \" has been added.");
            }
            forward = mapping.findForward("groupListing");
        } else if (groupForm.getGroupID() > 0) {
            UserGroupsDAO groupDao = new UserGroupsDAOImpl();
            UserGroups group = groupDao.getRow(groupForm.getGroupID());
            groupForm.setAction(groupForm.getAction());
            groupForm.setGroupID(group.getGroupID());
            groupForm.setGroupName(group.getGroupName());
            forward = mapping.findForward("groupEdit");
        } else {
            groupForm.setGroupID(0);
            forward = mapping.getInputForward();
        }
        return forward;
    }
}
